﻿using System;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using BLL;
using Model;

namespace Web.Areas.Manager.Controllers
{
    [NoCache]
    [HandleError]
    [UserAuthorize]
    public class TemplateController : Controller
    {
        Template_BLL _Template_BLL = new Template_BLL();
        Template_Type_BLL _Template_Type_BLL = new Template_Type_BLL();

        public virtual ActionResult Index(int? pageIndex, string keyword)
        {
            var model = _Template_BLL.Get();
            if (!string.IsNullOrEmpty(keyword))
            {
                model = model.Where(a => a.TemplateName.Contains(keyword));
            }
            return View(model.ToPagedList(pageIndex));
        }

        public virtual ActionResult Details(Guid id)
        {
            var item = _Template_BLL.Get(id);
            return View(item);
        }

        public virtual ActionResult Edit(Guid? id)
        {
            ViewData["Template_Type"] = _Template_Type_BLL.Get();

            var item = _Template_BLL.Get(id);

            using (FileStream fs = new FileStream(Server.MapPath("/Views/Shared/") + item.TemplateName + ".aspx", FileMode.OpenOrCreate, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    ViewData["template"] = sr.ReadToEnd();
                }
            }
            return View(item);
        }


        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Edit(Guid? id, Template collection, string template)
        {
            Edit(id);

            if (!ModelState.IsValid)
            {
                return View();
            }

            _Template_BLL.Save(id, ref collection);

            //保存更新模板 根据Id生成
            //模板保存位置 Shared

            using (StreamWriter sw = new StreamWriter(Server.MapPath("/Views/Shared/") + collection.TemplateName + ".aspx", false))
            {
                sw.Write(template);
            }

            return RedirectToAction("Index", RouteData.Values);

        }

        [HttpDelete]
        public virtual ActionResult Delete(Guid Id)
        {
            _Template_BLL.DeleteObject(Id);
            return RedirectToAction("Index", RouteData.Values);
        }
    }
}